<template>
  <a-modal
    :title="title"
    :width="1200"
    :ok=false
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="16">
          <a-col :lg="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="名称"
              :hidden="false"
              hasFeedback>
              <a-input id="departName" placeholder="请输入机构/店铺名称" v-decorator="['departName', validatorRules.departName ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :hidden="seen">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :hidden="seen" label="上级机构" hasFeedback>
              <a-tree-select
                style="width:100%"
                :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                :treeData="departTree"
                v-model="model.parentId"
                placeholder="请选择上级机构"
                :disabled="condition">
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="机构类型">
              <template v-if="seen">
                <a-radio-group v-decorator="['orgCategory',validatorRules.orgCategory]" placeholder="请选择机构类型">
                  <a-radio value="1">
                    公司
                  </a-radio>
                </a-radio-group>
              </template>
              <template v-else>
                <a-radio-group v-decorator="['orgCategory',validatorRules.orgCategory]" placeholder="请选择机构类型">
                  <a-radio value="2">
                    部门
                  </a-radio>
                  <a-radio value="3">
                    店铺
                  </a-radio>
                </a-radio-group>
              </template>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="16">
          <a-col :lg="8">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="编号">
              <a-input placeholder="自动生成编号" v-decorator="['storeId', {} ]" :disabled="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="16">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="margin-left: -102px"
              label="状态">
              <j-dict-select-tag  v-decorator="[ 'status', validatorRules.status ]" placeholder="状态" :type="'radioButton'" :triggerChange="true" dictCode="store_status"/>
            </a-form-item>
          </a-col>
        </a-row>


        <a-tabs v-model="activeKey" >
          <a-tab-pane tab="基本信息" key="1">
            <a-row class="form-row" :gutter="16">
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="联系人">
                  <a-input placeholder="请输入联系人" v-decorator="['linkName', {}]"/>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="联系电话">
                  <a-input placeholder="请输入联系电话" v-decorator="['phone', {}]"/>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="经营模式">
                  <j-dict-select-tag  v-decorator="['joinType', validatorRules.joinType]" placeholder="经营模式" :type="'radioButton'" :triggerChange="true" dictCode="join_type"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row class="form-row" :gutter="16">
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="所在地">
                  <a-cascader :options="areaData" v-model="areaValue" @change="onChange"
                              placeholder="请选择"/>
                </a-form-item>
              </a-col>
              <a-col :lg="16">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  style="margin-left: -102px"
                  label="详细地址">
                  <a-input placeholder="请输入详细地址" v-decorator="['address', {}]"/>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row class="form-row" :gutter="16">
              <a-col :lg="24">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  style="margin-left: -202px"
                  label="备注">
                  <a-textarea placeholder="请输入备注" v-decorator="['memo', {}]"/>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>

          <a-tab-pane tab="扩展信息" key="2" forceRender>
            <a-row class="form-row" :gutter="16">
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="经度">
                  <a-input-number v-decorator="[ 'longitude', {}]"/>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="纬度">
                  <a-input-number v-decorator="[ 'latitude', {}]"/>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="补货周期">
                  <a-input-number v-decorator="[ 'replenishmentDays', {}]"/>
                  <span> 天</span>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row class="form-row" :gutter="16">
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="开始营业">
                  <a-time-picker v-decorator="['dayTimeStart', {}]" valueFormat="HH:mm" format="HH:mm"/>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="结束营业">
                  <a-time-picker v-decorator="['dayTimeEnd', {}]" valueFormat="HH:mm" format="HH:mm"/>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="合同到期">
                  <a-date-picker format='YYYY-MM-DD HH:mm:ss' v-decorator="[ 'endTime', {}]"/>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row class="form-row" :gutter="16">
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="门店图标">
                  <a-upload
                    listType="picture-card"
                    class="logo-uploader"
                    :showUploadList="false"
                    :action="uploadAction"
                    :data="{'isup':1,'dir':'store/picture'}"
                    :headers="headers"
                    :beforeUpload="beforeUpload"
                    @change="handleChange"
                  >
                    <img v-if="pictureUrl" :src="getPictureView()" alt="logo" style="height:104px;max-width:300px"/>
                    <div v-else>
                      <a-icon :type="uploadLoading ? 'loading' : 'plus'"/>
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="门店logo">
                  <a-upload
                    listType="picture-card"
                    class="logo-uploader"
                    :showUploadList="false"
                    :action="uploadAction"
                    :data="{'isup':1,'dir':'store/logo'}"
                    :headers="headers"
                    :beforeUpload="beforeUpload"
                    @change="handleLogoChange"
                  >
                    <img v-if="logoUrl" :src="getLogoView()" alt="logo" style="height:104px;max-width:300px"/>
                    <div v-else>
                      <a-icon :type="uploadLogoLoading ? 'loading' : 'plus'"/>
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :lg="8">
                <a-form-item
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                  label="小程序码">
                  <a-upload
                    listType="picture-card"
                    class="logo-uploader"
                    :showUploadList="false"
                    :action="uploadAction"
                    :data="{'isup':1,'dir':'store/qrCode'}"
                    :headers="headers"
                    :beforeUpload="beforeUpload"
                    @change="handleQrCodeChange"
                  >
                    <img v-if="qrCodeUrl" :src="getQrCodeView()" alt="logo" style="height:104px;max-width:300px"/>
                    <div v-else>
                      <a-icon :type="uploadqrCodeLoading ? 'loading' : 'plus'"/>
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import { queryIdTree } from '@/api/api'
import pick from 'lodash.pick'
import moment from 'moment'
import Vue from 'vue'
import ATextarea from 'ant-design-vue/es/input/TextArea'

export default {
  name: 'DepartStoreModal',
  components: { ATextarea },
  data() {
    return {
      departTree: [],
      orgTypeData: [],
      phoneWarning: '',
      departName: '',
      title: '操作',
      seen: false,
      visible: false,
      condition: true,
      disableSubmit: false,
      model: {},
      menuhidden: false,
      menuusing: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      activeKey: '1',
      areaData: [],
      areaValue: [],
      confirmLoading: false,
      uploadLoading:false,
      uploadLogoLoading:false,
      uploadqrCodeLoading:false,
      headers:{},
      pictureUrl: "",
      logoUrl: "",
      qrCodeUrl: "",
      form: this.$form.createForm(this),
      validatorRules: {
        departName: { rules: [{ required: true, message: '请输入机构/店铺名称!' }] },
        orgCode: { rules: [{ required: true, message: '请输入机构编码!' }] },
        mobile: { rules: [{ validator: this.validateMobile }] },
        status: { rules: [{ required: true, message: '请选择状态!' }] },
        joinType: { rules: [{ required: true, message: '请选择经营模式!' }] },
      },
      url: {
        add: '/sys/sysDepartStore/add',
        areaJson: '/data/area',
        fileUpload: window._CONFIG['domianURL']+"/sys/common/ossUpload",
        imgerver: window._CONFIG['domianURL']+"/sys/common/view",
      },
      dictDisabled: true
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token":token};
  },
  computed:{
    uploadAction:function () {
      return this.url.fileUpload;
    }
  },
  methods: {
    loadTreeData() {
      var that = this
      queryIdTree().then((res) => {
        if (res.success) {
          that.departTree = []
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.departTree.push(temp)
          }
        }
      })
    },
    add(depart) {
      this.pictureUrl = "";
      this.logoUrl = "";
      this.qrCodeUrl = "";
      if (depart) {
        this.seen = false
        this.dictDisabled = false
      } else {
        this.seen = true
        this.dictDisabled = true
      }
      this.edit(depart)
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, {})
      this.visible = true
      this.activeKey = '1'
      this.loadTreeData()
      this.getArea()
      this.pictureUrl = this.model.picture;
      this.logoUrl = this.model.logo;
      this.qrCodeUrl = this.model.storeQrCode;
      this.areaValue = [this.model.provinceCode, this.model.cityCode, this.model.districtCode]
      this.model.parentId = record != null ? record.toString() : null
      if (this.seen) {
        this.model.orgCategory = '1'
      } else {
        this.model.orgCategory = '2'
      }
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'departName', 'orgCategory', 'storeId', 'status', 'linkName', 'phone', 'joinType', 'address', 'memo', 'longitude', 'latitude', 'replenishmentDays', 'dayTimeStart', 'dayTimeEnd'))
        this.form.setFieldsValue({ endTime: this.model.endTime ? moment(this.model.endTime) : null })
      })
    },
    beforeUpload: function(file){
      var fileType = file.type;
      if(fileType.indexOf('image')<0){
        this.$message.warning('请上传图片');
        return false;
      }
      //TODO 验证文件大小
    },
    handleChange (info) {
      this.pictureUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        let response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if(response.success){
          this.model.picture = response.message;
          this.pictureUrl = this.model.picture;
        }else{
          this.$message.warning(response.message);
        }
      }
    },
    getPictureView(){
      if(this.model.picture !== null && this.model.picture !== undefined && this.model.picture !== ''){
        if('http' === this.model.picture.substring(0,4)){
          return this.model.picture;
        }
        return this.url.imgerver +"/"+ this.model.picture;
      }
    },
    handleLogoChange (info) {
      this.logoUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadLogoLoading = true;
        return
      }
      if (info.file.status === 'done') {
        let response = info.file.response;
        this.uploadLogoLoading = false;
        console.log(response);
        if(response.success){
          this.model.logo = response.message;
          this.logoUrl = this.model.logo;
        }else{
          this.$message.warning(response.message);
        }
      }
    },
    getLogoView(){
      if(this.model.logo !== null && this.model.logo !== undefined && this.model.logo !== ''){
        if('http' === this.model.logo.substring(0,4)){
          return this.model.logo;
        }
        return this.url.imgerver +"/"+ this.model.logo;
      }
    },
    handleQrCodeChange (info) {
      this.qrCodeUrl = "";
      if (info.file.status === 'uploading') {
        this.uploadqrCodeLoading = true;
        return
      }
      if (info.file.status === 'done') {
        let response = info.file.response;
        this.uploadqrCodeLoading = false;
        console.log(response);
        if(response.success){
          this.model.storeQrCode = response.message;
          this.qrCodeUrl = this.model.storeQrCode;
        }else{
          this.$message.warning(response.message);
        }
      }
    },
    getQrCodeView(){
      if(this.model.storeQrCode !== null && this.model.storeQrCode !== undefined && this.model.storeQrCode !== ''){
        if('http' === this.model.storeQrCode.substring(0,4)){
          return this.model.storeQrCode;
        }
        return this.url.imgerver +"/"+ this.model.storeQrCode;
      }
    },
    close() {
      this.$emit('close')
      this.disableSubmit = false
      this.visible = false
    },
    getArea() {
      getAction(this.url.areaJson).then((res) => {
        this.areaData = res
      })
    },
    onChange(value, selectedOptions) {
      console.log(value, selectedOptions)
      if (selectedOptions != undefined) {
        this.model.provinceCode = selectedOptions[0].value
        this.model.cityCode = selectedOptions[1].value
        this.model.districtCode = selectedOptions[2].value
        this.model.province = selectedOptions[0].label
        this.model.city = selectedOptions[1].label
        this.model.district = selectedOptions[2].label
        this.areaValue = [this.model.provinceCode, this.model.cityCode, this.model.districtCode]
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          formData.name = formData.departName;
          formData.departOrder = formData.storeId;
          formData.mobile = formData.phone;
          formData.intro = formData.memo;
          formData.endTime = formData.endTime ? formData.endTime.format('YYYY-MM-DD HH:mm:ss') : null
          //时间格式化
          console.log(formData)
          httpAction(this.url.add, formData, 'post').then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadTreeData()
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })

        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback()
      } else {
        callback('您的手机号码格式不正确!')
      }

    }
  }
}
</script>

<style scoped>

</style>